package com.karina.visualization.chart.model;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.karina.visualization.chart.model.SeriesModel.CategoryValue;

public class CategorizedSeriesModel extends SeriesModel<List<CategoryValue>>
		implements HasMaxValue {
	private double max = 0.0;

	private Map<String, String> data = new HashMap<String, String>();

	@Override
	public void setValue(List<CategoryValue> obj) {
		super.setValue(obj);
		data = new HashMap<String, String>();
		for (CategoryValue value : obj) {
			try {
				double v = Double.parseDouble(value.getValue().toString());
				data.put(value.getCategory(), value.getValue().toString());
				if (v > max) {
					max = v;
				}
			} catch (Exception ex) {

			}
		}
	}

	protected String getValue(String category) {
		return data.get(category);
	}

	@Override
	public double getMaxValue() {
		return max;
	}

	@Override
	public void setMaxValue(double m) {
		max = m;
	}

	@Override
	protected DataModel<List<CategoryValue>> copy(
			DataModel<List<CategoryValue>> target) {
		CategorizedSeriesModel seriesM = (CategorizedSeriesModel) super
				.copy(target);

		setValue(new ArrayList<SeriesModel.CategoryValue>(getValue()));

		seriesM.max = max;

		return seriesM;
	}

	@Override
	public SeriesModel<List<CategoryValue>> cloneMe() {
		CategorizedSeriesModel model = new CategorizedSeriesModel();
		return (CategorizedSeriesModel) copy(model);
	}

	@Override
	protected DataModel<List<CategoryValue>> createStepModel(
			DataModel<List<CategoryValue>> t, double rate) {
		CategorizedSeriesModel newSeriesM = (CategorizedSeriesModel) super
				.createStepModel(t, rate);

		newSeriesM.max = ((CategorizedSeriesModel) t).max;

		List<CategoryValue> values = t.getValue();
		List<CategoryValue> newValues = new ArrayList<SeriesModel.CategoryValue>();

		for (CategoryValue value : values) {

			CategoryValue newValue = new CategoryValue();
			newValue.setCategory(value.getCategory());
			double currentValue = Double.parseDouble(this.getValue(value
					.getCategory()));
			double newV = Double.parseDouble(value.getValue().toString());
			int gap = (int) ((newV - currentValue) * rate);
			newValue.setValue("" + (currentValue + gap));

			newValues.add(newValue);
		}
		newSeriesM.setValue(newValues);

		return newSeriesM;
	}
}
